<template>
    <el-card shadow="never" class="common-card">
        <template #header>
            <el-row justify="space-between" align="middle">
                <h1>轮播管理</h1>
                <el-breadcrumb sepatrator="/">
                    <el-breadcrumb-item to="/control">管理首页</el-breadcrumb-item>
                    <el-breadcrumb-item to="/control/slide">轮播管理</el-breadcrumb-item>
                    <el-breadcrumb-item>轮播列表</el-breadcrumb-item>
                </el-breadcrumb>
            </el-row>
        </template>

        <div class="common-search">
            <el-form :inline="true" :model="queryForm">
                <el-form-item>
                    <el-button @click="delBatchByIds" type="danger" v-if="delIds.length > 0">批量删除</el-button>
                </el-form-item>
                <el-form-item label="选择审核">
                    <el-select style="width: 120px;" v-model.number="queryForm.status" placeholder="选择审核" clearable>
                        <el-option value="1" label="未审核" />
                        <el-option value="2" label="已审核" />
                    </el-select>
                </el-form-item>
                <el-form-item label="输入关键字">
                    <el-input style="width: 220px;" v-model.trim="queryForm.keyword" placeholder="请输入关键字" clearable />
                </el-form-item>

                <el-form-item>
                    <el-button circle>
                    <el-icon type="warning" @click="getSlideList">
                        <refresh />
                    </el-icon>
                </el-button>
                </el-form-item>
            </el-form>
            <el-button type="danger" @click="openDialog()">新增</el-button>
        </div>

        <el-table :ref="tableRef" :data="pageData" style="width: 100%;" stripe v-loading="loading"
            @selection-change="onselectionChange" border>
            <el-table-column type="selection" width="55" />
            <el-table-column label="排序" width="80" sortabel prop="orderId" />
            <el-table-column label="标题" width="150" prop="title" />
            <el-table-column label="缩图" width="180" #default="scope">
                <el-popover placement="top" :width="300" trigger="hover">
                    <el-image style="width: 100%;" :src="$baseAdminUrl + scope.row.picUrl" fit="cover" />
                    <template #reference>
                        <el-image style="width: 100%; height: 80px;" :src="$baseAdminUrl + scope.row.picUrl"
                            fit="cover" />
                    </template>
                </el-popover>
            </el-table-column>
            <el-table-column label="地址" prop="url" />
            <el-table-column label="状态" width="110" prop="status" #default="scope">
                <span color="red" v-if="scope.row.status === 1">未审核</span>
                <span color="green" v-else-if="scope.row.status === 2">已审核</span>
            </el-table-column>
            <el-table-column label="操作" width="150" #default="scope">
                <el-button plain type="primary" size="small" @click="openDialog(scope.row.id)">修改</el-button>
                <el-button plain type="danger" size="small" @click="delById(scope.row.id)">删除</el-button>
            </el-table-column>
        </el-table>

        <template #footer>
            <el-pagination background v-model:current-page="page" v-model:page-size="pageSize"
                :page-sizes="[2, 3, 4, 5, 6, 7, 8, 9, 10]" layout="total, sizes, prev, pager, next, jumper"
                :total="searchData.length" />
        </template>

    </el-card>


    <Teleport to="body">

        <el-dialog v-model="dialogVisible" :title="`${$editId === 0 ? '新增' : '修改'}轮播`" width="500">
            <el-form label-width="80px" :model="form" ref="formRef" :rules="rules">
                <el-form-item label="标题" prop="title">
                    <el-input v-model.trim="form.title" placeholder="请输入标题" clearable />
                </el-form-item>
                <el-form-item label="上传图片" prop="picUrl">
                    <el-tooltip effect="dark" content="请上传图片" placement="top">
                        <el-upload class="uploader" name="file" action="/api/manage/upload"
                            :headers="{ 'Authorrization': $authorization }" :show-file-list="false"
                            :on-success="onUploadSuccess" style="width: 500px; height: 160px;">
                            <img v-if="form.picUrl" :src="$baseAdminUrl + form.picUrl">
                            <el-icon :size="20" color="#8c939d" v-else>
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-tooltip>
                </el-form-item>
                <el-form-item label="链接" prop="url">
                    <el-input v-model="form.url" placeholder="请输入地址" clearable />
                </el-form-item>
                <el-form-item label="排序" prop="orderId">
                    <el-input-number v-model="form.orderId" clearable style="width: 180px;" min="0" />
                </el-form-item>
                <el-form-item label="审核">
                    <el-switch v-model="form.status" :active-value="2" :inactive-value="1" />
                </el-form-item>
                {{ form }}
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="addOrEditSlide">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </Teleport>

</template>

<script lang="ts" setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { slideList, slideDel, slideBatchDel, slideEditOrAdd, slideById } from '@/apis/slide';
import { ref, computed, reactive } from 'vue'
import type { ISlide, IApiResult } from '@/types';
import { Edit, Plus } from '@element-plus/icons-vue';

// 分页当前页码
const page = ref(1)
// 每页显示的数量
const pageSize = ref(4)
// 查询表单数据
const queryForm = reactive({
    status: '',
    keyword: ''
})

// 加载状态
const loading = ref(true);
// 表格数据
const tableData = ref([]);

// 获取轮播列表数据
const getSlideList = async () => {
    try {
        const res = await slideList();
        if (res.data.code !== 0) {
            ElMessage.error(res.data.desc);
            return
        }
        tableData.value = res.data.data;
        console.log(tableData.value);
        loading.value = false;
    } catch (err) {
        ElMessage.error(JSON.stringify(err));
    }
}
getSlideList();

// 根据查询条件搜索数据
const searchData = computed(() => {
    const { status, keyword } = queryForm;
    return tableData.value.filter((item: ISlide) => {
        return (status ? item.status === Number(status) : true) && item.title.includes(keyword)
    })
})

// 获取当前页的数据
const pageData = computed(() => {
    const start = (page.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return searchData.value.slice(start, end)
})

// 删除相关
// 已选择删除的ID列表
const delIds = ref<number[]>([]);
// 当选择项发生变化时更新已选择删除的ID列表
const onselectionChange = (val: ISlide[]) => {
    delIds.value = val.map((item: ISlide) => item.id) as number[]
}

// 根据ID删除单条轮播信息
const delById = async (id: number) => {
    try {
        const yes = await ElMessageBox.confirm('您确定要删除此条信息？', '提示', { type: 'warning' });
        if (!yes) return;
        const res = await slideDel(id);
        if (res.data.code !== 0) {
            ElMessage.error(res.data.desc);
            return
        }
        ElMessage.success('删除成功');
        getSlideList();
    } catch (err) {
        ElMessage.error(JSON.stringify(err))
    }
}

// 批量删除选中的轮播信息
const tableRef = ref();
const delBatchByIds = async () => {
    try {
        const yes = await ElMessageBox.confirm('您确定要删除所选信息？', '提示', { type: 'warning' });
        if (!yes) return;
        await slideBatchDel(delIds.value);
        ElMessage.success('删除成功');
        getSlideList();
    } catch (err) {
        if (err === 'cancel') {
            tableRef.value.clearSelection();
            return;
        }
    }
}

//新增修改相关

const dialogVisible = ref(false)
const formRef = ref()
const form = reactive({
    id: 0,
    orderId: 0,
    picUrl: '',
    status: 2,
    title: '',
    url: ''
})

//表单验证规则
const rules = reactive({
    title: { message: '请输入标题', required: true },
    picUrl: { message: '请上传图片', required: true },
    url: { message: '请输入地址', required: true },
    orderId: { message: '请输入排序号', required: true },
})

const $editId = ref(0)
//打开新增或修改弹窗

const openDialog = async (editId: number = 0) => {
    $editId.value = editId;
    if (editId) {
        try {
            const res = await slideById(editId);
            if (res.data.code !== 0) {
                ElMessage.error(res.data.desc);
                return
            }
            form.id = res.data.data.id;
            form.orderId = res.data.data.orderId;
            form.picUrl = res.data.data.picUrl;
            form.status = res.data.data.status;
            form.title = res.data.data.title;
            form.url = res.data.data.url;
        } catch (err) {
            ElMessage.error(JSON.stringify(err));
        }
    } else {
        formRef.value?.resetFields();
        form.id = 0;
        form.orderId = 0;
        form.picUrl = '';
        form.status = 2;
        form.title = '';
        form.url = '';
    }
    dialogVisible.value = true;
}


const addOrEditSlide = async () => {
    try {
        const isValid = await formRef.value.validate();
        if (!isValid) return;
        const res = await slideEditOrAdd(form);
        if (res.data.code !== 0) {
            ElMessage.error(res.data.desc);
            return
        }
        ElMessage.success(form.id ? '修改成功' : '新增成功');

        dialogVisible.value = false;
        getSlideList();
    } catch (err) {
        if (typeof err === 'string') ElMessage.error(JSON.stringify(err));
        console.error(err);

    }
}


const onUploadSuccess = (res: IApiResult) => {
    if (res.code !== 0) {
        ElMessage.error(res.msg);
        return
    }
    form.picUrl = res.data as string;
    ElMessage.success('上传成功');
}


</script>